import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import { Grid, Typography, Button, Avatar, IconButton } from '@material-ui/core';
import { CardBase } from 'components/organisms';
import { colors } from '@material-ui/core';
import ChatOutlined from '@material-ui/icons/ChatOutlined';
import { useSelector, useDispatch } from 'react-redux'
import { setFollowings } from 'redux/actions/FollowActions';
import { useHistory } from "react-router-dom";
import { setLoading, setCallbackError } from 'redux/actions/LoadingActions';
import { callPostApi } from 'utils/networking';

const useStyles = makeStyles(theme => ({
  answerCount: {
    padding: theme.spacing(1 / 2, 1),
    borderRadius: theme.spacing(1),
    background: theme.palette.secondary.light,
    color: 'white',
    fontWeight: 700,
    marginTop: theme.spacing(2),
  },
  buttonGrid: {
    width: '90%',
    marginTop: '30px',
    display: 'flex',
    justifyContent: 'center'
  },
  avatar: {
    width: '100px',
    height: '100px',  
  },
  title: {
    color: '#000',
    fontWeight: 'bold',
    marginTop: '20px',
    marginBottom: '10px'
  },
  divider: {
    width: '1px',
    height: '30px',
    marginTop: '5px',
    marginLeft: '10%',
    marginRight: '10%',
    backgroundColor: colors.grey[500]
  },
  follows: {
    width: '90%',
    marginTop: '20px',
    display: 'flex',
    justifyContent: 'center'
  },
  followButton: {
    width: '70%',
    backgroundColor: '#4051b5', 
    color: '#FFFFFF'
  },
  followingButton: {
    width: '70%',
    backgroundColor: '#6b096b', 
    color: '#FFFFFF'
  },
  listItemIcon: {
    width: '40px',
    height: '40px', 
    border: '2px solid',
    borderColor: colors.blue[900],
    marginLeft: '10%',
    display: 'flex',
    justifContent: 'center',
    alignItems: 'center'
  },
  closeIcon: {
    justifyContent: 'flex-end',
    cursor: 'pointer',
  }
}));

const User = props => {
  const { data, className, ...rest } = props;
  const classes = useStyles();
  const dispatch = useDispatch();
  const history = useHistory();
  const token = localStorage.getItem('token');
  
  const [followingStatus, setFollowingStatus] = useState(false);
  const [followersCount, setFollowersCount] = useState(data.followers_count);

  const profileData = useSelector((state) => state.auth.profileData)
  const followingsData = useSelector((state) => state.follow.followingsData)
  console.log('followingsData', followingsData)
  
  useEffect(() => {
    setFollowingStatus(getFollowingStatus(data.id))
  }, [followingsData])

  const getFollowingStatus = (userID) => {
    for (let following of followingsData) {
      //console.log(userID, following.followed_user_id);
      if (following.followed_user_id == userID && following.followed_status == 1) {
        return true;
      }
    }
    return false;
  }

  const updateFollowing = async (userID) => {
    if (!profileData || !profileData.id) {
      history.push(`signin`);
      return;
    }

    callPostApi('user/update_follow_status', { user_id: profileData.id, following_user_id: userID }, dispatch, (data) => {
      let isInFollowings = false;
      for (let index=0; index<followingsData.length; index++) {
        let following = followingsData[index];
        if (following.followed_user_id == userID) {
          isInFollowings = true;
          console.log('updated follow', data.follow);
          followingsData[index] = data.follow;
          break;
        }
      }
      if (!isInFollowings) {
        console.log('added follow', data.follow);
        followingsData.push(data.follow);
      }

      const followedStatus = (data.follow.followed_status == 1)
      let fc = followersCount;
      if (followedStatus) {
        fc = followersCount + 1
      } else {
        if (followersCount > 0) {
          fc = followersCount - 1
        }
      }
      setFollowersCount(fc)
      setFollowingStatus(followedStatus)
      dispatch(setFollowings(followingsData));
    })
  }

  return (
    <CardBase
      liftUp
      variant="outlined"
      style={{ borderTop: `5px solid ${colors.indigo[500]}` }}
      onClick={() => {
        window.location.href = `${process.env.REACT_APP_SERVER_URL}api/player/user/${data.id}/${token}`;
      }}
    >
      <Avatar {...{ src: data.avatarURL} } className={classes.avatar} />
      <Typography variant="body1" align="center" className={classes.title}>
        {data.username}
      </Typography>
      <Typography variant="body2" align="center">
        {data.full_name}
      </Typography>
      <div className={classes.follows}>
        <div>
          <Typography variant="body1" align="center">
            {followersCount}
          </Typography>
          <Typography variant="body1">
            Followers
          </Typography>
        </div>
        <div className={classes.divider}></div>
        <div>
          <Typography variant="body1" align="center">
            {data.following_count}
          </Typography>
          <Typography variant="body1">
            Followings
          </Typography>
        </div>
      </div>
      
      <div className={classes.buttonGrid}>
        <Button variant="contained" 
        className={followingStatus ? classes.followingButton : classes.followButton} 
        onClick={e => updateFollowing(data.id)}>
          {followingStatus ? "Following" : "Follow"}
        </Button>
        {/* <IconButton className={classes.listItemIcon} color="primary">
          <ChatOutlined fontSize="small" color="primary"/>
        </IconButton> */}
      </div>
    </CardBase>
  );
};

User.propTypes = {
  /**
   * External classes
   */
  className: PropTypes.string,
  /**
   * data to be rendered
   */
  data: PropTypes.object.isRequired,
};

export default User;
